import os
import random
import shutil
import re
import argparse
# 对labelme的输出json分别提炼到各自的目录：gt、raw

CopyFileParams={
    'json_file':'D:\wuxixian\HYM\demo\\rawImage\out\\fan1_json',
    'outFilepath':'D:\wuxixian\HYM\demo\\rawImage\out'
}
def copy_file(from_dir, to_dir, Name_list,dstName=None):
    if not os.path.isdir(to_dir):
        os.mkdir(to_dir)
    # 1
    # name_list = os.listdir(from_dir)
 
    # # 2
    # sample = random.sample(pathDir, 2)
    # print(sample)

    # 3
    for name in Name_list:
        try:
            if dstName is None:
                dstName=name
            # print(name)
            if not os.path.isfile(os.path.join(from_dir, name)):
                print("{} is not existed".format(os.path.join(from_dir, dstName)))
            shutil.copy(os.path.join(from_dir, name), os.path.join(to_dir, dstName))
            # print("{} has copied to {}".format(os.path.join(from_dir, name), os.path.join(to_dir, name)))
        except:
            # print("failed to move {}".format(from_dir + name))
            pass
        # shutil.copyfile(fileDir+name, tarDir+name)
    print("{} has copied to {}".format(from_dir, to_dir))

def handle():
    global CopyFileParams
    json_file = CopyFileParams['json_file']
    outFilepath=CopyFileParams['outFilepath']
    raw_to_Path=outFilepath+'\\'+'raw\\'
    gt_to_Path=outFilepath+'\\'+'gt\\'
    filepath_list = os.listdir(json_file)
    # 先清空
    try:
        import shutil
        shutil.rmtree(raw_to_Path)
        shutil.rmtree(gt_to_Path)
    except Exception  as e :
        print(e)
        
    # print(name_list)
    for i, file_path in enumerate(filepath_list):
        if file_path.endswith('_gt.png'):
            preName=file_path.replace('_gt.png','')
            preName=preName+'.png'

            # 复制图片
            print("copy {} to ...".format(os.path.join(json_file, preName)))
            copy_file(json_file, raw_to_Path, [preName])
            # 复制标签
            print("copy {} to ...".format(os.path.join(json_file, file_path)))
            copy_file(json_file, gt_to_Path, [file_path],preName)
        else:
            continue
    return raw_to_Path,gt_to_Path


# if __name__ == '__main__':
#     handle()
